//
//  SB_DaqingTuoluoyi.m
//  AppClient
//
//  Created by 张洪兴 on 2018/9/27.
//  Copyright © 2018年 Facebook. All rights reserved.
//

#import "SB_DaqingTuoluoyi.h"
#import <CoreMotion/CoreMotion.h>
@interface SB_DaqingTuoluoyi ()
{
  CMMotionManager * motionManager;
  
}
@end
@implementation SB_DaqingTuoluoyi

-(instancetype)init
{
  self = [super init];
  motionManager = [[CMMotionManager alloc] init];
  return self;
}

-(int)getSbDqBs{
  id sbDqBs = [[NSUserDefaults standardUserDefaults] objectForKey:@"sbDqBs"];
  int bs = 0;
  if (sbDqBs!=nil){
    bs = [sbDqBs intValue];
  }
  return bs;
}

-(void)startUpdateAccelerometer{
  NSTimeInterval updateInterval = 0.05;
  
  NSDate *date = [NSDate date];
  
  NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
  fmt.dateFormat = @"yyyy-MM-dd";
  
  NSString *now = [fmt stringFromDate:date];
  
  
  NSString * time = [[NSUserDefaults standardUserDefaults] objectForKey:@"sbDqTs"];
  if (![now isEqualToString:time]){
    
    [[NSUserDefaults standardUserDefaults] setObject:@(0) forKey:@"sbDqBs"];
  }
  [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"sbDqTs"];
  [[NSUserDefaults standardUserDefaults]synchronize];
  id sbDqBs = [[NSUserDefaults standardUserDefaults] objectForKey:@"sbDqBs"];
  int bs = 0;
  if (sbDqBs!=nil){
    bs = [sbDqBs intValue];
  }
  
  __block int stepCount = bs;
  if ([motionManager isAccelerometerAvailable] == YES) {
     [motionManager setAccelerometerUpdateInterval:updateInterval];
    
    
    [motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
      
      CGFloat sqrtValue= sqrt(accelerometerData.acceleration.x*accelerometerData.acceleration.x+accelerometerData.acceleration.y*accelerometerData.acceleration.y+accelerometerData.acceleration.z*accelerometerData.acceleration.z);
      if (sqrtValue > 1.552188){
        NSDate *date = [NSDate date];
        
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        
        NSString *now = [fmt stringFromDate:date];
        
        
        NSString * time = [[NSUserDefaults standardUserDefaults] objectForKey:@"sbDqTs"];
        if (![now isEqualToString:time]){
          
          stepCount = 0;
        }
        
          stepCount +=1;
        [[NSUserDefaults standardUserDefaults] setObject:@(stepCount) forKey:@"sbDqBs"];
        [[NSUserDefaults standardUserDefaults] setObject:now forKey:@"sbDqTs"];
        [[NSUserDefaults standardUserDefaults]synchronize];
      }
    }];
  }
}


@end
